use std::{fs::File, io::Write};

use byteorder::WriteBytesExt;
use cross_rs::IResult;



pub struct FileWriter {
    pub file: String,
    hndl: File,
}

impl FileWriter {
    pub fn new(file: String) -> IResult<Self> {
        let hndl = File::create(&file)?;
        Ok(Self { file, hndl })
    }
}

/*
\n : 换行符（newline），另起一行，对应ASCII 值10（缩写：LF）。 \r : 回车符（return），回到一行的开头，对应ASCII 值13（缩写：CR）。
    */
const ASCII_N: u8 = 10;
// const ASCII_R: u8 = 13;

impl FileWriter {
    pub fn write_bytes(&mut self, bts: &[u8]) -> IResult<usize> {
        let size = self.hndl.write(bts)?;
        Ok(size)
    }
    pub fn write_utf8(&mut self, content: &str) -> IResult<usize> {
        let bts = content.as_bytes();
        let size = self.hndl.write(bts)?;
        Ok(size)
    }
    pub fn write_newline(&mut self) -> IResult<usize> {
        self.hndl.write_u8(ASCII_N)?;
        Ok(1)
    }

    pub fn flush(&mut self) -> IResult{
        self.hndl.flush()?;
        Ok(())
    }
}

impl FileWriter {
    pub fn write_lines(file_utf8: &str, lines: &Vec<String>) -> IResult {
        let mut writer = Self::new(file_utf8.to_string())?;
        for line in lines {
            writer.write_utf8(line)?;
            writer.write_newline()?;
        }

        writer.flush()?;

        Ok(())
    }
}